<template>
  <section class="grant-main">
    <el-collapse-transition>
      <section class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.giveName"
          placeholder="输入福利名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <section class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </section>
      </section>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>定向福利</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px" @click="handleCreate">新建</el-button>
      </section>
    </section>

    <section class="main-tab">
      <el-tabs v-model="active" @tab-click="handleTabClick">
        <template v-for="item in types">
          <el-tab-pane :key="item.id" :name="item.id">
            <span slot="label">
              {{ item.name }}
              <el-popover
                placement="bottom"
                width="400"
                trigger="hover"
                :content="item.content"
              >
                <i slot="reference" class="el-icon-question" />
              </el-popover>

            </span>
          </el-tab-pane>
        </template>
      </el-tabs>
    </section>

    <section class="main-table">
      <v-table
        :list="list"
        :tag="flbFlag ? 'grantmain2' : 'grantmain' + active"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
      >
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleSend(scope.row)">
              {{ scope.row.publishStatus == "GIPSTSTUS01" ? "取消发布" : "发布" }}
            </el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
            <el-button type="text" size="mini" @click="handleUser(scope.row)">人员</el-button>
            <template v-if="scope.row.classifType === '2'">
              <el-button type="text" size="mini" @click="handleRefund(scope.row)">退款</el-button>
              <el-button type="text" size="mini" @click="handleRecord(scope.row)">订单</el-button>
            </template>
            <el-button
              v-if="scope.row.classifType === '0' && scope.row.useRange !== '2'"
              type="text"
              size="mini"
              @click="handleCommodity(scope.row)"
            >商品</el-button>
            <el-button type="text" size="mini" @click="handleStatistics(scope.row)">统计</el-button>
            <el-button type="text" size="mini" @click="handleConfig(scope.row)">配置</el-button>
            <el-button type="text" size="mini" @click="handleTip(scope.row)">提醒</el-button>
          </template>
        </el-table-column>
      </v-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </section>
    <!-- 发布时的弹窗 -->
    <el-dialog
      v-el-drag-dialog
      title="提示"
      custom-class="sendDialog"
      :show-close="false"
      :visible.sync="sendVisible"
      width="550px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div class="s-top">
        <div class="top-items">
          <div class="t-item">
            <div v-if="active==='0,2' || active==='1' || active==='7'" class="num">{{ chooseItem.issueCoinTotal||'0' }}</div>
            <div v-else class="num">{{ '---' }}</div>
            <div class="text">
              <span v-if="chooseItem.classifType==='0' || chooseItem.classifType==='2'">发放总金额</span>
              <span v-else-if="chooseItem.classifType==='1' || chooseItem.classifType==='7'">发放总张数</span>
            </div>
          </div>
          <div class="t-item">
            <div class="num">{{ chooseItem.issuePersonnelTotal||'0' }}</div>
            <div class="text">发放总人数</div>
          </div>
        </div>
        <div v-if="chooseItem.alreadyList && chooseItem.alreadyList.length>0" class="top-list">
          <div v-for="(item,i) in chooseItem.alreadyList" class="list-item">
            <div class="item-item"> <span class="item-text"> 红包金额（每人）：</span>{{ item.issueCoinTotal||'0' }}</div>
            <div class="item-item"><span class="item-text">红包人数（人）： </span> {{ item.issuePersonnelTotal||'0' }}</div>
          </div>
        </div>
      </div>
      <div class="s-bottom">
        <div class="b-item">
          <div class="name">福利名称：</div>
          <div class="value">{{ chooseItem.giveName||'' }}</div>
        </div>
        <div class="b-item">
          <div class="name">福利领取起止时间：</div>
          <div class="value">{{ (chooseItem['receiveStarttime'] && chooseItem['receiveStarttime']) + '至' + (
            chooseItem['receiveEndtime'] && chooseItem['receiveEndtime'])||'' }}</div>
        </div>
        <div class="b-item">
          <div class="name">福利使用起止时间：</div>
          <div class="value">{{ (chooseItem['expirationStartdate'] && chooseItem['expirationStartdate']) + '至' + (
            chooseItem['expirationDate'] && chooseItem['expirationDate'])||'' }}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sendVisible = false,chooseItem={}">取 消</el-button>
        <el-button style="background-color: #EB523C;color:#fff;" @click="handleStatus(chooseItem)">{{ btnMsg }}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      v-el-drag-dialog
      title="福利提醒"
      :show-close="false"
      :visible.sync="fromDataSourceVisible"
      width="550px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div class="sms-container">
        <el-checkbox-group v-model="sendType">
          <el-row style="padding:10px 0px;">
            <el-col :span="24" style="font-size:12px;color:red;">{{ msg }}</el-col>
          </el-row>
          <el-row style="font-size: 14px;">
            <el-col :span="12" style="padding:10px 0px;">未领取人数：<span class="red">{{ smsForm.notGiveNum }}</span>人</el-col>
            <el-col :span="12" class="check-col" style="padding:10px 0px;"><el-checkbox label="FL_WLQ">短信提醒</el-checkbox></el-col>
            <el-col :span="12">已领取且有余额人数：<span class="red">{{ smsForm.haveBalanceNum }}</span>人</el-col>
            <el-col :span="12" class="check-col"><el-checkbox label="FL_WXFW">短信提醒</el-checkbox></el-col>
          </el-row>

        </el-checkbox-group>
      </div>
      <span slot="footer">
        <el-button @click="fromDataSourceVisible = false,sendType=[]">取 消</el-button>
        <el-button style="background-color: #EB523C;color:#fff;" @click="handleSendSms">发送短信提醒</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import {
  getConfigByName,
  queryPage,
  del,
  getView,
  updatePublishStatus,
  sendSms,
  giveUseDetail
} from '../api/index'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'DirectionalIndex',
  components: {
    Pagination,
    VTable
  },
  directives: { elDragDialog },
  data() {
    return {
      active: '0,2,8',
      listQuery: {
        page: 1,
        limit: 10,
        giveName: ''
      },
      list: [],
      total: 0,
      listLoading: false,
      sendVisible: false,
      btnMsg: '',
      chooseItem: {},
      types: [],
      flbFlag: true,
      fromDataSourceVisible: false,
      fromDataSource: {},
      msg: '',
      sendType: [],
      smsForm: {},
      giveId: ''

    }
  },
  watch: {
    active(val) {
      if (val.indexOf('0') > -1 || val.indexOf('2') > -1 || val.indexOf('8') > -1) {
        this.flbFlag = true
      } else {
        this.flbFlag = false
      }
    }
  },
  created() {
    this.getClassType().then(() => {
      if (this.$route.query.t) {
        const type = this.types.find(a => {
          return a.id === this.$route.query.t
        })
        if (type) {
          this.active = this.$route.query.t
        } else {
          this.active = this.types[0].id
        }
      } else {
        this.active = this.types[0].id
      }
      this.getList()
    })
  },
  methods: {
    getClassType() {
      return new Promise((resolve, reject) => {
        getConfigByName({ name: 'WELFARE_SHOP_MALL_SHOW' }).then(res => {
          const str = res.data.data.configValue
          // if (str.indexOf('0') > -1 && str.indexOf('2') > -1 && str.indexOf('8') > -1) {
          //   this.types.push(
          //     {
          //       name: '福利包',
          //       id: '0,2,8',
          //       content: '向职工福利子账户发放一个福利包，福利包可以在线上福利商城，工会指定的线下门店使用。'
          //     },
          //   )
          // }
          // if ((str.indexOf('0') > -1 || str.indexOf('2') > -1 || str.indexOf('8') > -1) && this.types.length === 0) {
          //   this.types.push(
          //     {
          //       name: '福利包',
          //       id: str.indexOf('0') > -1 ? '0' : str.indexOf('2') > -1 ? '2' : str.indexOf('8') > -1 ? '8' : '',
          //       content: '向职工福利子账户发放一个福利包，福利包可以在线上福利商城，工会指定的线下门店使用。'
          //     },
          //   )
          // }

          // 循环设置福利包  福利包的值 0 2 8
          const flbArr = ['0', '2', '8']
          const flbVal = []
          for (let i = 0; i < flbArr.length; i++) {
            if (str.indexOf(flbArr[i]) > -1) {
              flbVal.push(flbArr[i])
            }
          }
          if (flbVal.length > 0) {
            this.types.push(
              {
                name: '福利包',
                id: flbVal.join(','),
                content: '向职工福利子账户发放一个福利包，福利包可以在线上福利商城，工会指定的线下门店使用。'
              },
            )
          }
          if (str.indexOf('1') > -1) {
            this.types.push({
              name: '兑换券',
              id: '1',
              content: '给职工发放一张线上商城的商品兑换券，职工可以使用该兑换券在线上商城兑换商品。'
            })
          }
          if (str.indexOf('7') > -1) {
            this.types.push(
              {
                name: '线下提货券',
                id: '7',
                content: '给职工发放一张线下实体店的商品提货券，职工可以使用该提货券在指定的线下实体门店兑换商品。'
              }
            )
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    filtercolumn(scope, item) {
      if (item === 'receiveTime') {
        return (scope.row['receiveStarttime'] && scope.row['receiveStarttime']) + '至' + (scope.row['receiveEndtime'] && scope.row['receiveEndtime'])
      } else if (item === 'expirationTime') {
        let str = ''
        if (scope.row['expirationStartdate'] && scope.row['expirationStartdate'] !== undefined) {
          str += scope.row['expirationStartdate']
        }
        if (scope.row['expirationDate'] && scope.row['expirationDate'] !== undefined) {
          str += '至' + scope.row['expirationDate']
        }
        return str
      } else if (item === 'classifType2') {
        return scope.row[item] || '--'
      } else if (item === 'classifType') {
        let str = ''
        if (scope.row[item] === '0') {
          str = '平台商城'
        } else if (scope.row[item] === '2') {
          str = '京东商城'
        } else if (scope.row[item] === '8') {
          str = '惠福商城'
        }
        return str
      } else {
        return scope.row[item]
      }
    },

    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.getList()
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.giveName = ''
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleCreate() {
      const t = this.active
      this.$router.push({
        path: this.$filterPath('create'),
        query: {
          t: t
        }
      })
    },

    handleUpdate(row) {
      this.$router.push({
        path: this.$filterPath('update'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },
    handleSend(row) {
      if (row.classifType === '2') {
        this.handleStatus(row)
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getView(row.id).then(async res => {
          loading.close()
          this.chooseItem = res.data.data || {}
          this.sendVisible = true
          if (this.chooseItem.publishStatus === 'GIPSTSTUS01') {
            this.btnMsg = '取消发布'
          } else {
            this.btnMsg = '发布'
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleStatus(row) {
      const state = row.publishStatus === 'GIPSTSTUS01' ? 'GIPSTSTUS02' : 'GIPSTSTUS01'
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        updatePublishStatus({
          id: row.id,
          publishStatus: state
        }).then(() => {
          loading.close()
          this.$message({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.sendVisible = false
          this.chooseItem = {}
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleUser(row) {
      this.$router.push({
        path: this.$filterPath('user'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },

    handleCommodity(row) {
      this.$router.push({
        path: this.$filterPath('commodity'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },
    handleStatistics(row) {
      const fromObj = {
        from: '/welfare/directional/index',
        t: this.active
      }
      const t = row.classifType
      const path = t === '0' || t === '1' ? this.$filterPath('activitystatistics4fy') : this.$filterPath('activitystatistics')
      this.$router.push({
        path: path,
        query: {
          id: row.id,
          couponMallId: row.couponMallId || '', // 兑换券统计要把兑换券的id传到下一页
          from: JSON.stringify(fromObj),
          c: row.classifType
        }
      })
    },
    /**
     * 退款
     * @param row
     */
    handleRefund(row) {
      this.$router.push({
        path: this.$filterPath('refundList'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },
    /**
     * 订单明细
     * @param row
     */
    handleRecord(row) {
      this.$router.push({ path: this.$filterPath('record'), query: { id: row.id, t: this.active }})
    },
    handleDelete(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          del(ids).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {})
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        classifType: this.active,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        giveName: this.listQuery.giveName
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    /**
     * 个性化配置
     * @param row
     */
    handleConfig(row) {
      this.$router.push({
        path: this.$filterPath('configuration'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },
    /**
     * 打开短信提醒弹窗
     */
    handleTip(row) {
      // todo 调查询发放人数详情接口后再打开
      this.giveId = row.id
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      giveUseDetail({
        giveId: row.id
      }).then(res => {
        loading.close()
        if (res.data.code === '200') {
          this.smsForm = res.data.data
          this.msg = res.data.data.lastResult
          this.fromDataSourceVisible = true
          this.sendType = []
        }
      }).catch(error => {
        loading.close(error)
      })
    },
    /**
     * 发送短信提醒
     */
    handleSendSms() {
      this.$confirm('确认发送短信提醒?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          sendSms({ giveId: this.giveId, sendSmsType: this.sendType.join(',') }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '发送成功',
              type: 'success',
              duration: 2000
            })
            this.fromDataSourceVisible = false
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {

      })
    }
  }
}
</script>
<style lang="scss">
.grant-main {
  padding: 10px;

  .sendDialog{
    .s-top{
      margin: 19px auto 0;
      width: 500px;
      opacity: 1;
      background: linear-gradient(#f25a44 0%, #ef7e46 99%);
      border-radius: 8px ;
      padding-bottom: 5px;
      .top-items{
        height: 74px;
        display: flex;
        justify-content: space-between;
        .t-item{
          height: 100%;
          flex: 1;
          color: #ffffff;
          text-align: center;
          padding-top: 21px;
          .num{
            font-size: 16px;
            font-family: PingFang SC Medium, PingFang SC Medium-Medium;
            font-weight: 500;
          }
          .text{
            margin-top: 5px;
            font-size: 14px;
            font-family: PingFang SC Regular, PingFang SC Regular-Regular;
            font-weight: 400;
          }
        }
      }
      .top-list{
        width: 450px;
        margin: 0 auto 5px auto;
        background: linear-gradient(0deg,#ffffff 0%, #ffffff 92%, #fc9c7e 100%);
        border-top: 6px solid #D8431B;
        opacity: 0.4, filter alpha(opacity=50);
        min-height: 55px;
        border-radius: 0 0 6px 6px;
        padding: 0 20px;
        position: relative;
        &:after{
          position: absolute;
          top: -6px;
          left: -10px;
          content: '';
          height: 12px;
          width: 10px;
          background: #D8431B;
          border-radius: 16px 0 0 16px;
        }
        &:before{
          position: absolute;
          top: -6px;
          right: -10px;
          content: '';
          height: 12px;
          width: 10px;
          background: #D8431B;
          border-radius: 0 16px  16px  0;
        }
        .list-item{
          height: 55px;
          display: flex;
          justify-content: space-between;
          color: #fff;
          border-bottom: 1px solid #eeeeee;
          box-sizing: border-box;
          &:last-child{
            border: none;
          }
          .item-item{
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            font-size: 14px;
            font-family: PingFang SC Regular, PingFang SC Regular-Regular;
            font-weight: 400;
            color: #333333;
            .item-text{
              color: #999999;
            }
          }
        }
      }
    }
    .s-bottom{
      margin: 0 auto 19px;
      width: 500px;
      height: 142px;
      opacity: 1;
      display: flex;
      flex-direction: column;
      .b-item{
        flex: 1;
        display: flex;
        align-items: center;
        font-size: 14px;
        font-family: PingFang SC Regular, PingFang SC Regular-Regular;
        font-weight: 400;
        border-bottom: 1px solid #eee;
        &:last-child{
          border: none;
        }
        .name{
          color: #999999;
        }
        .value{
          color: #333;
          font-weight: bold;
        }
      }
    }
    .el-dialog__footer{
      text-align: center !important;
    }
  }

  .main-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }

  .main-tab {
    width: 100%;
    margin-top: 10px;
    padding: 0 10px;
    background-color: #fff;
    display: flex;
    border-radius: 4px;
    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__header {
      margin: 0;
    }
  }
}
</style>
